using Microsoft.EntityFrameworkCore;
using PandaWebAPI.Models.ef;

namespace PandaWebAPI.Services;

/// <summary>
/// 购物车服务实现
/// </summary>
public class ShoppingCartService : IShoppingCartService
{
    private readonly PandaSystemContext _context;

    public ShoppingCartService(PandaSystemContext context)
    {
        _context = context;
    }

    /// <inheritdoc />
    public async Task<IEnumerable<ShoppingCart>> GetAllAsync()
    {
        return await _context.ShoppingCarts
            .Include(sc => sc.User)
            .Include(sc => sc.CartItems)
            .ToListAsync();
    }

    /// <inheritdoc />
    public async Task<ShoppingCart?> GetByIdAsync(Guid id)
    {
        return await _context.ShoppingCarts
            .Include(sc => sc.User)
            .Include(sc => sc.CartItems)
            .FirstOrDefaultAsync(sc => sc.CartId == id);
    }

    /// <inheritdoc />
    public async Task<ShoppingCart?> GetByUserIdAsync(Guid userId)
    {
        return await _context.ShoppingCarts
            .Include(sc => sc.User)
            .Include(sc => sc.CartItems)
            .FirstOrDefaultAsync(sc => sc.UserId == userId);
    }

    /// <inheritdoc />
    public async Task<ShoppingCart> CreateAsync(ShoppingCart shoppingCart)
    {
        shoppingCart.CartId = Guid.NewGuid();
        shoppingCart.CreatedAt = DateTime.UtcNow;
        _context.ShoppingCarts.Add(shoppingCart);
        await _context.SaveChangesAsync();
        return shoppingCart;
    }

    /// <inheritdoc />
    public async Task<ShoppingCart> UpdateAsync(ShoppingCart shoppingCart)
    {
        _context.Entry(shoppingCart).State = EntityState.Modified;
        await _context.SaveChangesAsync();
        return shoppingCart;
    }

    /// <inheritdoc />
    public async Task DeleteAsync(Guid id)
    {
        var shoppingCart = await _context.ShoppingCarts
            .Include(sc => sc.CartItems)
            .FirstOrDefaultAsync(sc => sc.CartId == id);
            
        if (shoppingCart != null)
        {
            // 删除购物车项
            _context.CartItems.RemoveRange(shoppingCart.CartItems);
            // 删除购物车
            _context.ShoppingCarts.Remove(shoppingCart);
            await _context.SaveChangesAsync();
        }
    }

    /// <inheritdoc />
    public async Task ClearCartAsync(Guid cartId)
    {
        var shoppingCart = await _context.ShoppingCarts
            .Include(sc => sc.CartItems)
            .FirstOrDefaultAsync(sc => sc.CartId == cartId);
            
        if (shoppingCart != null)
        {
            _context.CartItems.RemoveRange(shoppingCart.CartItems);
            await _context.SaveChangesAsync();
        }
    }
} 